﻿using System;
using System.Reflection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using net.xBei.Helper;
using xBei.Redis.Extension;

namespace net.xBei.WebApi.Filters {
    /// <summary>
    /// 过期API过滤器
    /// </summary>
    public class ObsoleteActionFilter(RedisClient redisClient) : IActionFilter {
        /// <inheritdoc/>
        public void OnActionExecuted(ActionExecutedContext context) {
            var action = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor);
            var obs = action.MethodInfo.GetCustomAttribute<ObsoleteAttribute>();
            if (obs != null) {
                context.HttpContext.Response.Headers.Append("obsolete", "obsolete");
            }
        }
        /// <inheritdoc/>
        public void OnActionExecuting(ActionExecutingContext context) {
            var action = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor);
            var obs = action.MethodInfo.GetCustomAttribute<ObsoleteAttribute>();
            if (obs == null) {
                return;
            }
            Console.WriteLine(context.ActionDescriptor.DisplayName + " 过期：" + obs.Message);
            _ = redisClient.EnqueueAsync($"ObsoleteApi:{action.ControllerName}:{action.ActionName}({action.MethodInfo.Name})",
                new {
                    DateTime.UtcNow,
                    route = action.AttributeRouteInfo?.Template,
                    //Template = "api/v1/Goods/ProductAndGoods"
                    action.DisplayName,
                }.ToJson(true));
        }
    }
}
